<template>
  <div class="quill_box">
    <quill-editor
      v-model="content"
      ref="myQuillEditor"
      :options="editorOption"
      @blur="onEditorBlur($event)"
      @focus="onEditorFocus($event)"
      @change="onEditorChange($event)"
    >
    </quill-editor>
    <el-upload
      v-show="false"
      :show-file-list="false"
      :name="uploadImgConfig.file"
      :multiple="false"
       ref="upload"
      :action="uploadImgConfig.uploadUrl"
      :before-upload="onBeforeUpload"
      :on-success="onSuccess"
      :on-error="onError"
      :file-list="fileList"
    >
      <!--<i class="el-icon-upload"></i>-->
      <!--<div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>-->
      <!--<div class="el-upload__tip" slot="tip">最多只能上传两个附件</div>-->
      <button ref="myinput">上传文件</button>
    </el-upload>
  </div>
</template>
<script>
  import 'quill/dist/quill.core.css';
  import 'quill/dist/quill.snow.css';
  import 'quill/dist/quill.bubble.css';
  // import  quillEditor  from 'vue-quill-editor';
  import * as Quill from 'quill'  // 引入编辑器
  import ImageResize from 'quill-image-resize-module';
  import { ImageDrop } from 'quill-image-drop-module'; // 图片拖动组件引用
  Quill.register('modules/imageResize',ImageResize);
  Quill.register('modules/imageDrop', ImageDrop); // 注册

  const toolbarOptions = [
    ['bold', 'italic', 'underline', 'strike'],
    ['blockquote', 'code-block'],
    [{ list: 'ordered' }, { list: 'bullet' }],
    [{ script: 'sub' }, { script: 'super' }],
    [{ indent: '-1' }, { indent: '+1' }],
    [{ size: ['small', false, 'large', 'huge'] }],
    [{ font: [] }],
    [{ color: [] }, { background: [] }],
    [{ align: [] }],
    ["image"],
  ]
  export default {
    // components: {
    //   quillEditor
    // },
    data() {
      return {
        loading: false, // 加载loading
        content: '',
        editorOption: {
          placeholder: '请输入内容',
          modules: {
            toolbar: {
              container: toolbarOptions, //工具栏
              headers: {
                image: function(value) {
                  if (value) {
                    // 获取隐藏的上传图片的class，不一定是.el-icon-plus。触发上传图片事件
                    document.querySelector('.ql-image').click()
                  } else {
                    this.quill.format('image', false)
                  }
                },
              }
            },
            imageDrop: true,      //图片拖拽
            imageResize: {
              displayStyles: {
                backgroundColor: "black",
                border: "none",
                color: "white",
              },
              modules: ["Resize", "DisplaySize", "Toolbar"],
            },
          }
        },
        // 图片上传变量
        fileList: []
      }
    },
    props: {
      contentDefault: {
        type: String,
        default: ''
      },
      imgUrl: {
        type: String,
        default: ''
      },
      uploadImgConfig: {
        type: Object,
        default() {
          return {
            uploadUrl: '/jcsj/punishnotice/saveImg', // 图片上传地址
            file: 'file' // 图片上传字段
          }
          }
          }
        },
    watch: {
      contentDefault: function () {
        this.content = this.contentDefault
      }
    },

    mounted() {
    this.init()
    },
    methods: {
      init() {
        const editor = this.$refs.myQuillEditor;//dom元素
        //创建
        // 定义图片上传事件
        if (this.uploadImgConfig.uploadUrl) {
          let toolbar = this.$refs['myQuillEditor'].quill.getModule('toolbar')
          toolbar.addHandler("image", (value) => {
            if (value) {
              this.$refs.upload.$children[0].$refs.input.click();
            } else {
              this.quill.format('image', false)
            }
          });
        }
      },

      hideLoading() {
        this.loading = false
      },

      // 把已经上传的图片显示回富文本编辑框中
      uploadSuccess(imgurl) {
        let quill = this.$refs['myQuillEditor'].quill
        let range = quill.getSelection()
        let index = 0
        if (range == null) {
          index = 0
        } else {
          index = range.index // 获取光标所在位置
        }
        // 插入
        quill.insertEmbed(index, 'image', imgurl) // imgurl是服务器返回的图片链接地址
        // 调整光标到最后
        quill.setSelection(index + 1)
      },
      // el-文件上传组件
      onBeforeUpload(file) {
        this.loading = true
        let acceptArr = ['image/jpg', 'image/jpeg', 'image/gif', 'image/png']
        const isIMAGE = acceptArr.includes(file.type)
        // const isLt1M = file.size / 1024 / 1024 < this.uploadImgConfig.maxSize
        if (!isIMAGE) {
          this.hideLoading()
          this.$message.error('只能插入图片格式!')
        }
        // if (!isLt1M) {
        //   this.hideLoading()
        //   this.$message.error(
        //     `上传文件大小不能超过 ${this.uploadImgConfig.maxSize}MB!`
        //   )
        // }
        // return isLt1M && isIMAGE
        return isIMAGE
      },
      // 文件上传成功时的钩子
      onSuccess(response, file, fileList) {
        // ---- 注意这部分需要改为对应的返回格式
        this.hideLoading()
        if (response.code === 0) {
          this.uploadSuccess(response.data)
        } else {
          this.$message.error('上传失败')
        }
      },
      // 文件上传失败时的钩子
      onError(file, fileList)
      {
      },

      // --------- 图片上传相关 end ---------

      onEditorBlur() {
        //失去焦点事件
        // console.log('失去焦点');
      },
      onEditorFocus() {
        //获得焦点事件
        // console.log('获得焦点事件');
      },
      onEditorChange() {
        //内容改变事件
        // console.log('内容改变事件');
        this.$emit('child-event', this.content)
        // console.log('this.content', this.content)
      }
    }
  }
</script>
<style>
  .quill_box .ql-toolbar.ql-snow {
    border-color: #dcdfe6;
  }
  .quill_box .ql-container {
    height: 200px !important;
    border-color: #dcdfe6;
  }
  .quill_box .ql-snow .ql-picker-label::before {
    position: relative;
    top: -10px;
  }
  .quill_box .ql-snow .ql-color-picker .ql-picker-label svg,
  .ql-snow .ql-icon-picker .ql-picker-label svg {
    position: relative;
    top: -6px;
  }
</style>
